package phone.qyg.com.qyg.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.adapter.recycler.CommonAdapter;
import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.adapter.recycler.RecyclerViewItemDecoration;
import com.app.adapter.recycler.base.ViewHolder;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PromptManager;
import com.app.utils.TransformController;
import com.app.view.BaseViewStateLayout;
import com.app.xutils.MyCallBack;
import com.app.xutils.Xutils;
import com.liaoinstan.springview.container.AliFooter;
import com.liaoinstan.springview.container.AliHeader;
import com.liaoinstan.springview.widget.SpringView;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.adapter.CultureTypeAdapter;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.Culture;
import phone.qyg.com.qyg.model.Roll;
import phone.qyg.com.qyg.utils.AppHttpRequest;

/**
 * 作者：lblbh on 2018/1/5 10:42
 * 邮箱：lanbuhan@163.com
 * 功能：文化超市列表
 */
@ContentView(R.layout.culture_list)
public class CultureListActivity extends BaseActivity {

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.one_recycler)
    RecyclerView one_recycler;

    @ViewInject(R.id.two_recycler)
    RecyclerView two_recycler;

    @ViewInject(R.id.there_recycler)
    RecyclerView there_recycler;

    @ViewInject(R.id.linear)
    LinearLayout linear;

    BaseViewStateLayout baseView;

    SpringView springview;

    RecyclerView recycler;

    List<Base> nodes;

    List<Base> resInfos;

    List<Base> units;

    Base node;

    Base resInfo;

    Base unit;

    CommonAdapter adapter;

    List<Culture> models;

    boolean isForce;

    int page_no,totalpage;

    int special_id;

    String title;

    @Override
    public void initSucessView() {
        Object obj = getTransModels();
        if(obj instanceof Base){
            Base base = (Base) obj;
            special_id = base.id;
            title = base.title;
        }else if(obj instanceof Roll){
            Roll roll = (Roll) obj;
            special_id = roll.objectId;
            title = roll.title;
        }


        mapKeys.put(AppHttpKey.SUB_ID,String.valueOf(special_id));
        AppHttpRequest.httpRequestDefalut(ApplicationConfig.RESINFO_SELECT_CONDITION,
                mapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState && JSONTool.isStatus(result)){
                            //资源栏目
                            nodes =  JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.NODE_LIST,Base.class);
                            //资源类别
                            resInfos =  JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.RES_INFO_TYPE_LIST,Base.class);
                            //所属单位
                            units =  JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.UNIT_LIST,Base.class);

                            setNodes(nodes);

                            setResInfos(resInfos);

                            setUnits(units);

                            getInitNetwork(false);
                        }
                    }
                });

        baseView = new BaseViewStateLayout(QXApplication.getContext()) {

            @Override
            public View obtionView() {
                View sucessView = View.inflate(QXApplication.getContext(), R.layout.base_spring_recycler,null);
                recycler = (RecyclerView) sucessView.findViewById(R.id.recycler);
                LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
                layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);
                recycler.addItemDecoration(new RecyclerViewItemDecoration(
                            RecyclerViewItemDecoration.MODE_HORIZONTAL,
                            getResources().getColor(R.color.divider),
                            CommonUtil.dip2px(QXApplication.getContext(),1),0,0));
                recycler.setLayoutManager(layoutVerManager);
                springview = (SpringView) sucessView.findViewById(R.id.springview);

                springview.setListener(new SpringView.OnFreshListener() {
                    @Override
                    public void onRefresh() {
                        isForce = true;
                        getInitNetwork(false);
                    }

                    @Override
                    public void onLoadmore() {
                        if(isRequestList(models) && (page_no < totalpage) ){
                            getInitNetwork(true);
                        }else{
                            PromptManager.showToast(R.string.more_no_datas);
                            springview.onFinishFreshAndLoad();
                        }

                    }
                });

                springview.setHeader(new AliHeader(QXApplication.getContext(),false));
                springview.setFooter(new AliFooter(QXApplication.getContext(),false));
                return sucessView;
            }

            @Override
            public Object obtionData() {
                return DELFAUTSTATE;
            }
        };

        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        linear.addView(baseView,layoutParams);
        x.view().inject(linear);
    }



    /**
     * 执行网络请求
     */
    private void getInitNetwork(final boolean isPull){

        if(isPull){
            page_no = page_no + 1;
        }else{
            page_no = 1;
        }

        if(isForce){
            page_no = 1;
        }

        /**
         *     “subId”:1//专题id
         “type’:1//资源类型
         “nodeId”:1//资源栏目id
         “publishUnit”:”所属单位”

         */


        mapKeys.put(AppHttpKey.SUB_ID,String.valueOf(special_id));
        mapKeys.put(AppHttpKey.TYPE,getCultureType(resInfo));
        mapKeys.put(AppHttpKey.NODE_ID,getCultureType(node));
        mapKeys.put(AppHttpKey.PUBLISH_UNIT,(null != unit)?unit.title:"全部");
        mapKeys.put(AppHttpKey.PAGE_NO,String.valueOf(page_no));

        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.TRES_INFO_LIST,
                mapKeys,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);

                        List<Culture> temps = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.RES_INFO_LIST, Culture.class);

                        totalpage = JSONTool.requestJSONfindNameCount(result,JSONTool.Enum.DATA,JSONTool.Enum.TOTALPAGE);

                        if(!isRequestList(temps) && !isPull){
                            baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_EMPTY);
                            baseView.stateView();
                            return;
                        }
                        //成功获取到数据
                        baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_SUCESS);
                        baseView.stateView();

                        setModelData(isPull,temps);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_ERROE);
                        baseView.stateView();
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                        springview.onFinishFreshAndLoad();
                    }
                });
    }


    private void setModelData(final boolean isPull, List<Culture> temps) {
        if ((adapter == null && isRequestList(temps)) || isForce) {
            isForce = false;

            //数据初始化工作
            models = temps;

            adapter = new CommonAdapter<Culture>(QXApplication.getContext(),R.layout.item_culture,models) {
                @Override
                protected void convert(ViewHolder holder, Culture model, int position) {
                    holder.setText(R.id.item_title,model.title);
                    holder.setText(R.id.item_state,model.pubTime);
                    holder.setText(R.id.item_author,model.author);
                    holder.setImage(R.id.item_img,model.fixImgUrl, OptionImageUtils.getRectRatio43());
                }
            };

            adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    Culture model = (Culture) adapter.getDatas().get(position);
                    int type = model.type;
                    //类型 0、文档 1、图片 2、视频 3、音频'
                    Class clazz = null;
                    if(type == 0){
                        //文档
                        clazz = CultureFileDetailActivity.class;
                    }else if(type == 1){
                        //图片
                        clazz = CultureImgDetailActivity.class;
                    }else if(type == 2){
                        //视频
                        clazz = CultureVideoDetailActivity.class;
                    }

                    if(null != clazz)
                        TransformController.transformControllerModel(QXApplication.getContext(), clazz,model);
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }
            });


            recycler.setAdapter(adapter);

        }

        if (isPull && isRequestList(models) && isRequestList(temps)) {
            //上拉加载数据
            models.addAll(temps);
        }

//        //刷新数据
        if (adapter != null)
            adapter.notifyDataSetChanged();
    }

    /**
     * 设置资源列表
     * @param nodes
     */
    private void setNodes(final List<Base> nodes){
        if(!isRequestList(nodes))return;
        node = nodes.get(0);
        node.hintType = 1;

        final CultureTypeAdapter adapter = new CultureTypeAdapter(QXApplication.getContext(),nodes);
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        one_recycler.setLayoutManager(layoutVerManager);
        one_recycler.setAdapter(adapter);

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Base itemBase = adapter.getDatas().get(position);

                if(node == itemBase)return;

                node.hintType = 0;
                itemBase.hintType = 1;
                node = itemBase;

                adapter.notifyDataSetChanged();
                isForce = true;
                getInitNetwork(false);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    /**
     * 设置资源类别
     * @param resInfos
     */
    private void setResInfos(final List<Base> resInfos){
        if(!isRequestList(resInfos))return;
        resInfo = resInfos.get(0);
        resInfo.hintType = 1;

        final CultureTypeAdapter adapter = new CultureTypeAdapter(QXApplication.getContext(),resInfos);
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        two_recycler.setLayoutManager(layoutVerManager);
        two_recycler.setAdapter(adapter);

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Base itemBase = adapter.getDatas().get(position);

                if(resInfo == itemBase)return;

                resInfo.hintType = 0;
                itemBase.hintType = 1;
                resInfo = itemBase;

                adapter.notifyDataSetChanged();
                isForce = true;
                getInitNetwork(false);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    /**
     * 设置所属单位
     * @param units
     */
    private void setUnits(final List<Base> units){
        if(!isRequestList(units))return;
        unit = units.get(0);
        unit.hintType = 1;

        final CultureTypeAdapter adapter = new CultureTypeAdapter(QXApplication.getContext(),units);
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        there_recycler.setLayoutManager(layoutVerManager);
        there_recycler.setAdapter(adapter);

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Base itemBase = adapter.getDatas().get(position);

                if(unit == itemBase)return;

                unit.hintType = 0;
                itemBase.hintType = 1;
                unit = itemBase;

                adapter.notifyDataSetChanged();
                isForce = true;
                getInitNetwork(false);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }


    /**
     * 获取筛分项 id 默认全部1
     * @param base
     * @return
     */
    private String getCultureType(Base base){
        int type = -1;

        if(null != base){
            type = base.id;
        }
        return String.valueOf(type);
    }

    @Event(value = {R.id.back})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        back.setText(setAttributeText(title));
    }

    @Override
    public void initViewHandler() {}
}
